<template>
  <div class="dictionary-management-container">
    <el-row :gutter="20">
      <!-- 字典类型列表 -->
      <el-col :span="8">
        <el-card class="dict-type-card">
          <template #header>
            <div class="card-header">
              <span>字典类型</span>
              <el-button type="primary" @click="handleAddDictType">新增字典类型</el-button>
            </div>
          </template>
          
          <el-table
            :data="dictTypes"
            style="width: 100%"
            highlight-current-row
            @current-change="handleDictTypeSelect"
            v-loading="loading.type"
          >
            <el-table-column prop="name" label="类型名称" />
            <el-table-column prop="code" label="类型编码" width="180" />
            <el-table-column label="状态" width="80">
              <template #default="scope">
                <el-tag :type="scope.row.status ? 'success' : 'danger'">
                  {{ scope.row.status ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="160">
              <template #default="scope">
                <el-button
                  size="small"
                  @click.stop="handleEditDictType(scope.row)"
                >
                  编辑
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click.stop="handleDeleteDictType(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页组件 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="typeQuery.page"
              v-model:page-size="typeQuery.size"
              :page-sizes="[10, 20, 30, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="typeTotal"
              @size-change="handleTypePageSizeChange"
              @current-change="handleTypePageChange"
            />
          </div>
        </el-card>
      </el-col>
      
      <!-- 字典数据列表 -->
      <el-col :span="16">
        <el-card class="dict-data-card">
          <template #header>
            <div class="card-header">
              <span>
                字典数据
                <el-tag v-if="currentDictType" type="primary" style="margin-left: 8px;">
                  {{ currentDictType.name }}
                </el-tag>
              </span>
              <el-button
                type="primary"
                @click="handleAddDictData"
                :disabled="!currentDictType"
              >
                新增字典数据
              </el-button>
            </div>
          </template>
          
          <el-table
            :data="dictDataList"
            style="width: 100%"
            v-loading="loading.data"
          >
            <el-table-column prop="label" label="字典标签" />
            <el-table-column prop="value" label="字典键值" width="120" />
            <el-table-column prop="cssClass" label="CSS类名" width="150" />
            <el-table-column label="状态" width="80">
              <template #default="scope">
                <el-tag :type="scope.row.status ? 'success' : 'danger'">
                  {{ scope.row.status ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="orderNum" label="排序" width="80" />
            <el-table-column prop="remark" label="备注" width="200" />
            <el-table-column label="操作" width="160">
              <template #default="scope">
                <el-button
                  size="small"
                  @click="handleEditDictData(scope.row)"
                >
                  编辑
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="handleDeleteDictData(scope.row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 分页组件 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="dataQuery.page"
              v-model:page-size="dataQuery.size"
              :page-sizes="[10, 20, 30, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="dataTotal"
              @size-change="handleDataPageSizeChange"
              @current-change="handleDataPageChange"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 字典类型表单对话框 -->
    <el-dialog
      v-model="dictTypeDialog.visible"
      :title="dictTypeDialog.title"
      width="500px"
    >
      <el-form
        :model="dictTypeForm"
        :rules="dictTypeRules"
        ref="dictTypeFormRef"
        label-width="100px"
      >
        <el-form-item label="类型名称" prop="name">
          <el-input v-model="dictTypeForm.name" placeholder="请输入类型名称" />
        </el-form-item>
        <el-form-item label="类型编码" prop="code">
          <el-input
            v-model="dictTypeForm.code"
            placeholder="请输入类型编码"
            :disabled="dictTypeDialog.isEdit"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="dictTypeForm.status" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="dictTypeForm.remark"
            type="textarea"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dictTypeDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitDictTypeForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 字典数据表单对话框 -->
    <el-dialog
      v-model="dictDataDialog.visible"
      :title="dictDataDialog.title"
      width="500px"
    >
      <el-form
        :model="dictDataForm"
        :rules="dictDataRules"
        ref="dictDataFormRef"
        label-width="100px"
      >
        <el-form-item label="字典标签" prop="label">
          <el-input v-model="dictDataForm.label" placeholder="请输入字典标签" />
        </el-form-item>
        <el-form-item label="字典键值" prop="value">
          <el-input v-model="dictDataForm.value" placeholder="请输入字典键值" />
        </el-form-item>
        <el-form-item label="字典类型" prop="typeCode">
          <el-input v-model="dictDataForm.typeCode" disabled />
        </el-form-item>
        <el-form-item label="CSS类名" prop="cssClass">
          <el-input v-model="dictDataForm.cssClass" placeholder="请输入CSS类名" />
        </el-form-item>
        <el-form-item label="排序" prop="orderNum">
          <el-input-number v-model="dictDataForm.orderNum" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="dictDataForm.status" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="dictDataForm.remark"
            type="textarea"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dictDataDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitDictDataForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { dictAPI } from '@/api/api'

export default {
  name: 'DictionaryManagement',
  setup() {
    // 字典类型数据相关
    const dictTypes = ref([])
    const currentDictType = ref(null)
    const typeTotal = ref(0)
    const typeQuery = reactive({
      page: 1,
      size: 10
    })
    
    // 字典数据列表相关
    const dictDataList = ref([])
    const dataTotal = ref(0)
    const dataQuery = reactive({
      page: 1,
      size: 10,
      typeCode: ''
    })
    
    // 加载状态
    const loading = reactive({
      type: false,
      data: false
    })
    
    // 字典类型对话框相关
    const dictTypeDialog = reactive({
      visible: false,
      title: '新增字典类型',
      isEdit: false
    })
    
    // 字典数据对话框相关
    const dictDataDialog = reactive({
      visible: false,
      title: '新增字典数据',
      isEdit: false
    })
    
    // 字典类型表单相关
    const dictTypeFormRef = ref(null)
    const dictTypeForm = reactive({
      id: null,
      name: '',
      code: '',
      status: true,
      remark: ''
    })
    
    // 字典类型表单验证规则
    const dictTypeRules = {
      name: [
        { required: true, message: '请输入类型名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
      ],
      code: [
        { required: true, message: '请输入类型编码', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
      ]
    }
    
    // 字典数据表单相关
    const dictDataFormRef = ref(null)
    const dictDataForm = reactive({
      id: null,
      label: '',
      value: '',
      typeCode: '',
      cssClass: '',
      orderNum: 0,
      status: true,
      remark: ''
    })
    
    // 字典数据表单验证规则
    const dictDataRules = {
      label: [
        { required: true, message: '请输入字典标签', trigger: 'blur' },
        { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
      ],
      value: [
        { required: true, message: '请输入字典键值', trigger: 'blur' },
        { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
      ],
      typeCode: [
        { required: true, message: '请选择字典类型', trigger: 'blur' }
      ]
    }
    
    // 获取字典类型列表
    const fetchDictTypes = async () => {
      loading.type = true
      try {
        const response = await dictAPI.getDictTypes({
          page: typeQuery.page,
          size: typeQuery.size
        })
        
        if (response.success) {
          dictTypes.value = response.data.list || []
          typeTotal.value = response.data.totalItems || 0
        } else {
          ElMessage.error('获取字典类型列表失败: ' + response.message)
        }
      } catch (error) {
        console.error('获取字典类型列表失败:', error)
        ElMessage.error('获取字典类型列表失败: ' + (error.message || '未知错误'))
      } finally {
        loading.type = false
      }
    }
    
    // 获取字典数据列表
    const fetchDictData = async () => {
      if (!currentDictType.value) {
        dictDataList.value = []
        dataTotal.value = 0
        return
      }
      
      dataQuery.typeCode = currentDictType.value.code
      
      loading.data = true
      try {
        const response = await dictAPI.getDictData(dataQuery.typeCode, {
          page: dataQuery.page,
          size: dataQuery.size
        })
        
        if (response.success) {
          dictDataList.value = response.data.list || []
          dataTotal.value = response.data.totalItems || 0
        } else {
          ElMessage.error('获取字典数据列表失败: ' + response.message)
        }
      } catch (error) {
        console.error('获取字典数据列表失败:', error)
        ElMessage.error('获取字典数据列表失败: ' + (error.message || '未知错误'))
      } finally {
        loading.data = false
      }
    }
    
    // 选择字典类型
    const handleDictTypeSelect = (row) => {
      if (row) {
        currentDictType.value = row
        dataQuery.page = 1
        fetchDictData()
      } else {
        currentDictType.value = null
        dictDataList.value = []
        dataTotal.value = 0
      }
    }
    
    // 新增字典类型
    const handleAddDictType = () => {
      dictTypeDialog.title = '新增字典类型'
      dictTypeDialog.isEdit = false
      resetDictTypeForm()
      dictTypeDialog.visible = true
    }
    
    // 编辑字典类型
    const handleEditDictType = (row) => {
      dictTypeDialog.title = '编辑字典类型'
      dictTypeDialog.isEdit = true
      resetDictTypeForm()
      
      // 复制行数据到表单
      Object.assign(dictTypeForm, {
        id: row.id,
        name: row.name,
        code: row.code,
        status: row.status,
        remark: row.remark || ''
      })
      
      dictTypeDialog.visible = true
    }
    
    // 删除字典类型
    const handleDeleteDictType = (row) => {
      ElMessageBox.confirm(
        `确定要删除字典类型"${row.name}"吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(async () => {
          try {
            const response = await dictAPI.deleteDictType(row.id)
            
            if (response.success) {
              ElMessage.success('删除字典类型成功')
              
              // 如果删除的是当前选中的类型，清空选择
              if (currentDictType.value && currentDictType.value.id === row.id) {
                currentDictType.value = null
                dictDataList.value = []
                dataTotal.value = 0
              }
              
              fetchDictTypes()
            } else {
              ElMessage.error('删除字典类型失败: ' + response.message)
            }
          } catch (error) {
            console.error('删除字典类型失败:', error)
            ElMessage.error('删除字典类型失败: ' + (error.message || '未知错误'))
          }
        })
        .catch(() => {
          ElMessage.info('已取消删除')
        })
    }
    
    // 提交字典类型表单
    const submitDictTypeForm = () => {
      if (!dictTypeFormRef.value) return
      
      dictTypeFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            const formData = { ...dictTypeForm }
            
            const response = dictTypeDialog.isEdit
              ? await dictAPI.updateDictType(formData)
              : await dictAPI.addDictType(formData)
            
            if (response.success) {
              ElMessage.success(dictTypeDialog.isEdit ? '编辑字典类型成功' : '新增字典类型成功')
              dictTypeDialog.visible = false
              
              // 刷新字典类型列表
              fetchDictTypes()
              
              // 如果编辑的是当前选中的类型，更新选中的类型
              if (dictTypeDialog.isEdit && currentDictType.value && currentDictType.value.id === formData.id) {
                currentDictType.value = { ...currentDictType.value, ...formData }
              }
            } else {
              ElMessage.error((dictTypeDialog.isEdit ? '编辑字典类型失败: ' : '新增字典类型失败: ') + response.message)
            }
          } catch (error) {
            console.error(dictTypeDialog.isEdit ? '编辑字典类型失败:' : '新增字典类型失败:', error)
            ElMessage.error((dictTypeDialog.isEdit ? '编辑字典类型失败: ' : '新增字典类型失败: ') + (error.message || '未知错误'))
          }
        }
      })
    }
    
    // 重置字典类型表单
    const resetDictTypeForm = () => {
      if (dictTypeFormRef.value) {
        dictTypeFormRef.value.resetFields()
      }
      
      dictTypeForm.id = null
      dictTypeForm.name = ''
      dictTypeForm.code = ''
      dictTypeForm.status = true
      dictTypeForm.remark = ''
    }
    
    // 新增字典数据
    const handleAddDictData = () => {
      if (!currentDictType.value) {
        ElMessage.warning('请先选择字典类型')
        return
      }
      
      dictDataDialog.title = '新增字典数据'
      dictDataDialog.isEdit = false
      resetDictDataForm()
      
      // 设置当前选中的字典类型
      dictDataForm.typeCode = currentDictType.value.code
      
      dictDataDialog.visible = true
    }
    
    // 编辑字典数据
    const handleEditDictData = (row) => {
      dictDataDialog.title = '编辑字典数据'
      dictDataDialog.isEdit = true
      resetDictDataForm()
      
      // 复制行数据到表单
      Object.assign(dictDataForm, {
        id: row.id,
        label: row.label,
        value: row.value,
        typeCode: row.typeCode,
        cssClass: row.cssClass || '',
        orderNum: row.orderNum,
        status: row.status,
        remark: row.remark || ''
      })
      
      dictDataDialog.visible = true
    }
    
    // 删除字典数据
    const handleDeleteDictData = (row) => {
      ElMessageBox.confirm(
        `确定要删除字典数据"${row.label}"吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(async () => {
          try {
            const response = await dictAPI.deleteDictData(row.id)
            
            if (response.success) {
              ElMessage.success('删除字典数据成功')
              fetchDictData()
            } else {
              ElMessage.error('删除字典数据失败: ' + response.message)
            }
          } catch (error) {
            console.error('删除字典数据失败:', error)
            ElMessage.error('删除字典数据失败: ' + (error.message || '未知错误'))
          }
        })
        .catch(() => {
          ElMessage.info('已取消删除')
        })
    }
    
    // 提交字典数据表单
    const submitDictDataForm = () => {
      if (!dictDataFormRef.value) return
      
      dictDataFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            const formData = { ...dictDataForm }
            
            const response = dictDataDialog.isEdit
              ? await dictAPI.updateDictData(formData)
              : await dictAPI.addDictData(formData)
            
            if (response.success) {
              ElMessage.success(dictDataDialog.isEdit ? '编辑字典数据成功' : '新增字典数据成功')
              dictDataDialog.visible = false
              fetchDictData()
            } else {
              ElMessage.error((dictDataDialog.isEdit ? '编辑字典数据失败: ' : '新增字典数据失败: ') + response.message)
            }
          } catch (error) {
            console.error(dictDataDialog.isEdit ? '编辑字典数据失败:' : '新增字典数据失败:', error)
            ElMessage.error((dictDataDialog.isEdit ? '编辑字典数据失败: ' : '新增字典数据失败: ') + (error.message || '未知错误'))
          }
        }
      })
    }
    
    // 重置字典数据表单
    const resetDictDataForm = () => {
      if (dictDataFormRef.value) {
        dictDataFormRef.value.resetFields()
      }
      
      dictDataForm.id = null
      dictDataForm.label = ''
      dictDataForm.value = ''
      dictDataForm.typeCode = currentDictType.value ? currentDictType.value.code : ''
      dictDataForm.cssClass = ''
      dictDataForm.orderNum = 0
      dictDataForm.status = true
      dictDataForm.remark = ''
    }
    
    // 分页相关
    const handleTypePageSizeChange = (newSize) => {
      typeQuery.size = newSize
      typeQuery.page = 1
      fetchDictTypes()
    }
    
    const handleTypePageChange = (newPage) => {
      typeQuery.page = newPage
      fetchDictTypes()
    }
    
    const handleDataPageSizeChange = (newSize) => {
      dataQuery.size = newSize
      dataQuery.page = 1
      fetchDictData()
    }
    
    const handleDataPageChange = (newPage) => {
      dataQuery.page = newPage
      fetchDictData()
    }
    
    // 生命周期钩子
    onMounted(() => {
      fetchDictTypes()
    })
    
    return {
      // 字典类型相关
      dictTypes,
      currentDictType,
      typeTotal,
      typeQuery,
      dictTypeDialog,
      dictTypeFormRef,
      dictTypeForm,
      dictTypeRules,
      handleDictTypeSelect,
      handleAddDictType,
      handleEditDictType,
      handleDeleteDictType,
      submitDictTypeForm,
      handleTypePageSizeChange,
      handleTypePageChange,
      
      // 字典数据相关
      dictDataList,
      dataTotal,
      dataQuery,
      dictDataDialog,
      dictDataFormRef,
      dictDataForm,
      dictDataRules,
      handleAddDictData,
      handleEditDictData,
      handleDeleteDictData,
      submitDictDataForm,
      handleDataPageSizeChange,
      handleDataPageChange,
      
      // 其他
      loading
    }
  }
}
</script>

<style scoped>
.dictionary-management-container {
  padding: 20px;
}

.dict-type-card,
.dict-data-card {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 